﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SQLite;
using System.Text;

namespace Com.Toook.Common
{
    /// <summary>
    ///PageData 保存各个分类的记录总数、标题、关键字、描述信息
    /// </summary>
    public class PageData
    {
        //PageColumn字段顺序必须和PageData中的sql查询列顺序相同
        private static string sqlPageParam = " select id, typeId, typeCode, typeName, totalCount, title, keyword, description, newsSiteId from ShowPageParam;";
        private static string sqlNewsSite = " select SiteId, SiteName from RssSites;";
        private static string sqlTypeParam = "select typeId, typeCode, typeName, parentId, grandId from TypeParam; ";
        /// <summary>
        /// 保存各个分类记录总数、标题、关键字、描述信息
        /// </summary>
        private static DataTable typeParamTable = new DataTable();
        /// <summary>
        /// 保存showPageParamTable表中的分页、标题、关键字、描述信息
        /// </summary>
        private static DataTable showPageParamTable = new DataTable();

        /// <summary>
        /// 保存新闻站点类型名称
        /// </summary>
        private static DataTable newsSiteTable = new DataTable();
        public PageData()
        {
        }
        /// <summary>
        /// TypeParam表 根据condition(如"typeId=12", "parentId=10")获取匹配行的数据,没有返回null
        /// </summary>
        /// <param name="condition"></param>
        /// <returns>没有返回null</returns>
        public static DataRow SelectTypeParamRow(string condition)
        {
            if (typeParamTable.Rows.Count == 0)
            {
                InitPageData();
            }

            DataRow[] rows = null;
            try
            {
                rows = typeParamTable.Select(condition);
            }
            catch
            {
                LogHelper.Log.Error("SelectTypeParamRow()错误. " + condition);
                return null;
            }
            if(rows != null && rows.Length > 0)
            {
                return rows[0];
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 根据id获取对应的地区名称(欧美、大陆)
        /// </summary>
        /// <param name="areaId">地区id</param>
        /// <returns></returns>
        public static string GetArea(object areaId)
        {
            string area = "未知";
            if (areaId != null && areaId.ToString() != "")
            {
                area = GetTypeName(areaId.ToString());
                if (area == null)
                {
                    area = "未知";
                }
            }          
            return area;
        }
        /// <summary>
        /// 根据类型id获取电影类型名称(喜剧、动作)
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        public static string GetMovieTypeName(object typeId)
        {
            string name = "电影";
            if (typeId != null && typeId.ToString() != "")
            {
                name = GetTypeName(typeId.ToString());
                if (name == null)
                {
                    name = "电影";
                }
            }
            return name;
        }
        /// <summary>
        /// 从表TypeParam，根据typeId获取typeName. 没有对应的返回null
        /// </summary>
        /// <param name="typeId"></param>
        /// <returns></returns>
        public static string GetTypeName(string typeId)
        {
            string typeName = null;
            if (string.IsNullOrEmpty(typeId))
            {
                return typeName;
            }
            DataRow row = SelectTypeParamRow("typeId=" + typeId);
            if (row != null)
            {
                typeName = row["typeName"].ToString();
            }
            return typeName;
        }
        /// <summary>
        /// 获取ShowPageParam表中的行数据。没有满足的返回null
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public static DataRow SelectParamRow(string condition)
        {
            if (showPageParamTable.Rows.Count == 0)
            {
                InitPageData();
            }

            DataRow[] rows = showPageParamTable.Select(condition);

            if (rows.Length > 0)
            {
                return rows[0];
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 根据新闻站点ID，获取新闻站点RssSites数据
        /// </summary>
        /// <param name="newsSiteId">新闻站点id.如101</param>
        /// <returns></returns>
        public static DataRow SelectNewsSiteRow(string newsSiteId)
        {
            if(newsSiteTable.Rows.Count == 0)
            {
                InitPageData();
            }

            DataRow[] rows = newsSiteTable.Select("SiteId=" + newsSiteId);

            if(rows.Length > 0)
            {
                return rows[0];
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 根据byCondition查询出行数据，再获取columnName指定列的值
        /// </summary>
        /// <param name="byCondition">条件(如"typeId=2", "typeName='movie2' ")</param>
        /// <param name="columnName">要获取值的列名枚举PageColumn</param>
        /// <returns>没有返回null</returns>
        public static object GetValue(string byCondition, string columnName)
        {
            DataRow row = SelectParamRow(byCondition);
            if(row != null)
            {
                return row[columnName];
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 计算分页开始值 limit start, pageSize
        /// </summary>
        /// <param name="page">从url获取的page参数</param>
        /// <param name="total">记录总数</param>
        /// <param name="pageSize">没有显示数</param>
        /// <returns></returns>
        public static int CalculateStart(string page, int total, int pageSize)
        {
            int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;//总页数
            int p;
            //页数不为空且是数字，设置页码。否则第一页。
            if(!string.IsNullOrEmpty(page))
            {
                int.TryParse(page, out p);
            }
            else
            {
                p = 1;
            }
            //分页参数不合法
            if(p < 1 || p > pageCount)
            {
                p = 1;
            }

            int start = (p - 1) * pageSize;

            return start;
        }
        /// <summary>
        /// 生成分页代码
        /// </summary>
        /// <param name="total">总数</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageHref">要替换页的url,用页数替换pageN: list.aspx?其他参数page=pageN其他参数</param>
        /// <returns></returns>
        public static string GetPageHtml(int total, int pageSize, int currentPage, string pageHref)
        {
            string remark = "pageN";
            StringBuilder sb = new StringBuilder();
            if (total > pageSize)
            {
                int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;//总页数
                                
                //显示当前页 前、后多少页
                int showPre = 2, showNext = 7;//前2 后7 共10页
                int start, end;
                if (currentPage - showPre <= 1)
                {
                    start = 1;
                }
                else
                {
                    start = currentPage - showPre;
                    sb.Append("<a href=\"" + pageHref.Replace(remark, "1") + "\">首页</a>");
                }

                end = pageCount - currentPage <= showNext ? pageCount : currentPage + showNext;
                if (currentPage > 1)
                {
                    sb.Append("<a href=\"" + pageHref.Replace(remark, (currentPage - 1).ToString()) + "\">上一页</a>");
                }

                for (int i = start; i <= end; i++)
                {
                    sb.Append("<a href=\"" + pageHref.Replace(remark, i.ToString()) + "\" ");
                    if (i == currentPage)
                    {
                        sb.Append(" class=\"curentPage\"");
                    }
                    sb.Append(">" + i.ToString());
                    sb.Append("</a>");
                }
                if (currentPage < pageCount)
                {
                    sb.Append("<a href=\"" + pageHref.Replace(remark, (currentPage + 1).ToString()) + "\">下一页</a>");
                }
                if (pageCount - currentPage > showNext)
                {
                    sb.Append("<a href=\"" + pageHref.Replace(remark, pageCount.ToString()) + "\">尾页</a>");
                }
                sb.Append(" 共" + pageCount.ToString() + "页");
            }

            return sb.ToString();
        }
        /// <summary>
        /// 查询数据库，初始化类型分页数据表typeParamTable
        /// </summary>
        public static void InitPageData()
        {
            SQLiteConnection con = SqliteHelper.GetConnection("SQLiteDatabase");
            SQLiteDataAdapter da = new SQLiteDataAdapter(sqlPageParam + sqlNewsSite + sqlTypeParam, con);
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds);

                showPageParamTable = ds.Tables[0];
                newsSiteTable = ds.Tables[1];
                typeParamTable = ds.Tables[2];
            }
            catch(Exception ex)
            {
                LogHelper.Log.Fatal("初始化公共参数、新闻站点错误。InitPageData()", ex);
            }            
        }
    }

    /// <summary>
    ///PageColumn ShowPageParam表中的字段名
    /// </summary>
    public class PageColumn
    {
        public PageColumn()
        {
        }
        public static string id = "id";
        /// <summary>
        /// 分类的数字ID。如30 
        /// </summary>
        public static string typeId = "typeId";
        /// <summary>
        /// 分类名称加ID。如movie31 
        /// </summary>
        public static string typeCode = "typeCode";
        /// <summary>
        /// 分类名称
        /// </summary>
        public static string typeName = "typeName";
        /// <summary>
        /// 此分类总记录数
        /// </summary>
        public static string totalCount = "totalCount";
        /// <summary>
        /// 此分类页面标题
        /// </summary>
        public static string title = "title";
        /// <summary>
        /// 此分类页面关键字
        /// </summary>
        public static string keyword = "keyword";
        /// <summary>
        /// 此分类页面描述
        /// </summary>
        public static string description = "description";
        /// <summary>
        /// 此新闻分类中站点id列表.逗号隔开，如：101,102,105
        /// </summary>
        public static string newsSiteId = "newsSiteId";
    }
}